import React, { useState } from 'react';
import { 
  Upload, Button, Card, message, Typography, 
  Alert, Spin, Descriptions, Table, Space 
} from 'antd';
import { 
  UploadOutlined, InboxOutlined, 
  CheckCircleOutlined, ExclamationCircleOutlined 
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api from '../utils/api';

const { Dragger } = Upload;
const { Title, Paragraph } = Typography;

const DataUpload = () => {
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [dataInfo, setDataInfo] = useState(null);
  const navigate = useNavigate();
  
  // 处理文件上传
  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择要上传的文件');
      return;
    }
    
    const formData = new FormData();
    formData.append('file', fileList[0].originFileObj);
    
    setUploading(true);
    
    try {
      const response = await api.uploadData(formData);
      setDataInfo(response.data);
      setUploadSuccess(true);
      message.success('文件上传成功');
    } catch (error) {
      console.error('上传失败:', error);
      let errorMsg = '文件上传失败';
      
      if (error.response && error.response.data) {
        errorMsg = error.response.data.message || errorMsg;
      }
      
      message.error(errorMsg);
    } finally {
      setUploading(false);
    }
  };
  
  // 处理文件选择变化
  const handleFileChange = ({ fileList }) => {
    // 限制只能上传一个文件
    setFileList(fileList.slice(-1));
    // 重置上传状态
    setUploadSuccess(false);
    setDataInfo(null);
  };
  
  // 文件上传控件的属性
  const uploadProps = {
    name: 'file',
    multiple: false,
    fileList,
    onChange: handleFileChange,
    beforeUpload: (file) => {
      const isExcelOrCsv = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                          file.type === 'application/vnd.ms-excel' ||
                          file.type === 'text/csv' ||
                          file.name.endsWith('.xlsx') ||
                          file.name.endsWith('.xls') ||
                          file.name.endsWith('.csv');
      
      if (!isExcelOrCsv) {
        message.error('只能上传Excel或CSV文件!');
      }
      
      return isExcelOrCsv ? false : Upload.LIST_IGNORE;
    },
    customRequest: ({ onSuccess }) => {
      setTimeout(() => {
        onSuccess("ok");
      }, 0);
    }
  };
  
  // 创建数据预览表格
  const createDataPreviewTable = () => {
    if (!dataInfo || !dataInfo.column_names) return null;
    
    const columns = dataInfo.column_names.map((name, index) => ({
      title: name,
      dataIndex: name,
      key: name,
      ellipsis: true,
      width: 120,
    }));
    
    // 由于我们没有实际的数据内容，这里只显示表格头
    return (
      <div style={{ marginTop: '24px', overflowX: 'auto' }}>
        <Title level={4}>数据预览</Title>
        <Alert 
          message="数据已加载，可以进行分析" 
          type="success" 
          showIcon 
          icon={<CheckCircleOutlined />}
          style={{ marginBottom: '16px' }}
        />
        <Table 
          columns={columns} 
          dataSource={[]}  // 这里需要后端提供实际数据
          pagination={false}
          scroll={{ x: 'max-content' }}
          size="small"
        />
      </div>
    );
  };
  
  // 导航到分析页面
  const goToAnalysis = (type) => {
    navigate(`/${type.toLowerCase()}`);
  };
  
  return (
    <div>
      <Title level={2}>数据上传</Title>
      <Paragraph>
        请上传您需要分析的数据文件。支持Excel(.xlsx)和CSV(.csv)格式。
      </Paragraph>
      
      <Card title="上传数据文件" bordered={false}>
        <Dragger {...uploadProps} style={{ marginBottom: '16px' }}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持Excel(.xlsx)和CSV(.csv)文件，建议数据量不超过1MB
          </p>
        </Dragger>
        
        <Button
          type="primary"
          onClick={handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{ marginTop: '16px' }}
        >
          {uploading ? '上传中...' : '开始上传'}
        </Button>
      </Card>
      
      {uploading && (
        <div style={{ textAlign: 'center', margin: '24px 0' }}>
          <Spin tip="上传处理中..." />
        </div>
      )}
      
      {uploadSuccess && dataInfo && (
        <Card title="数据信息" style={{ marginTop: '24px' }}>
          <Descriptions bordered>
            <Descriptions.Item label="文件名称">
              {fileList[0]?.name || '未知'}
            </Descriptions.Item>
            <Descriptions.Item label="行数">
              {dataInfo.rows}
            </Descriptions.Item>
            <Descriptions.Item label="列数">
              {dataInfo.columns}
            </Descriptions.Item>
          </Descriptions>
          
          {createDataPreviewTable()}
          
          <div style={{ marginTop: '24px' }}>
            <Title level={4}>选择分析方法</Title>
            <Space>
              <Button 
                type="primary" 
                onClick={() => goToAnalysis('ICA')}
              >
                ICA分析
              </Button>
              <Button 
                onClick={() => goToAnalysis('AE')}
              >
                AE分析
              </Button>
              <Button 
                onClick={() => goToAnalysis('PCA')}
              >
                PCA分析
              </Button>
              <Button 
                onClick={() => goToAnalysis('PLS')}
              >
                PLS分析
              </Button>
            </Space>
          </div>
        </Card>
      )}
    </div>
  );
};

export default DataUpload; 